package com.kernowsoft.wavefx;

import java.util.ArrayList;

import com.kernowsoft.wavefx.R;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

public class SiteSelectorActivity extends FragmentActivity implements
		LoaderManager.LoaderCallbacks<Cursor> {

	private static final String TAG = "SiteSelectorActivity";
	//private ArrayList<String> mAllSites;
	
	private ListView mSiteList;
	
	// menu ids:
	private static final int ID_MENU_REFRESH_SITES = Menu.FIRST;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// inflate the content:
		setContentView(R.layout.layout_select_site);
		
		// get view references:
		mSiteList = (ListView)findViewById(R.id.listMatchingSites);
		
		// new cursor adaptor (we will set cursor reference later):
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
				null, new String[] {WaveDataContentProvider.Locations.NAME},
				new int[] {android.R.id.text1}, SimpleCursorAdapter.NO_SELECTION);
		
		mSiteList.setAdapter(adapter);
		
		// inialise the cursor loader:
		// (int id, Bundle args, LoaderCallbacks<D> callback)
		getSupportLoaderManager().initLoader(0, null, this);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		switch(item.getItemId()) {
		case ID_MENU_REFRESH_SITES:
			intent = new Intent(this, ForecastUpdateService.class);
			intent.setAction(ForecastUpdateService.REQUEST_SITELIST_UPDATE);
			startService(intent);
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		menu.add(Menu.NONE, ID_MENU_REFRESH_SITES, Menu.NONE, "Refresh Sites");
		return true;
	}
	
	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {

		String[] projection = { WaveDataContentProvider.Locations._ID,
				WaveDataContentProvider.Locations.NAME };
		
		Log.d(TAG, "Creating new cursor loader");
		return new CursorLoader(this, WaveDataContentProvider.Locations.CONTENT_URI,
				projection, null, null, null);

	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		((SimpleCursorAdapter)mSiteList.getAdapter()).swapCursor(cursor);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		((SimpleCursorAdapter)mSiteList.getAdapter()).swapCursor(null);

	}
}
